<script setup lang="ts">
import type { GetReadingHistoryParams, ReadingHistoryRespVO, ReadingStatsRespVO } from '@/types/reading-records'
import { onLoad, onPullDownRefresh, onReachBottom, onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'
import {
  clearAllReadingRecords,
  deleteReadingRecord,
  formatReadingDate,
  getReadingHistory,
  getReadingStats,
  getRecordKey,
  handleReadingRecordsError,
  processBookCover,
} from '@/api/reading-records'
import { checkLoginStatus } from '@/utils/auth'

// 弹窗引用
const deletePopup = ref()
const clearPopup = ref()

// 状态管理
const loading = ref(false)
const loadMoreStatus = ref('more')
const deleteRecord = ref<ReadingHistoryRespVO | null>(null)

// 数据存储
const records = ref<ReadingHistoryRespVO[]>([])
const stats = ref<ReadingStatsRespVO | null>(null)

// 分页参数
const pageParams = ref({
  page: 1,
  size: 20,
})

// 是否还有更多数据
const hasMore = ref(true)

// 加载阅读统计
async function loadReadingStats() {
  try {
    const response = await getReadingStats()
    if (response && response.code === 0 && response.data) {
      stats.value = response.data
    }
  }
  catch (error: any) {
    console.error('加载阅读统计失败:', error)

    // 检查是否是401错误（已经在拦截器中处理跳转）
    if (error?.data?.code === 401 || error?.statusCode === 401) {
      console.log('401错误已处理，用户将跳转到登录页面')
    }
  }
}

// 加载阅读记录
async function loadReadingRecords(isRefresh = false) {
  try {
    if (isRefresh) {
      pageParams.value.page = 1
      hasMore.value = true
    }

    loading.value = isRefresh || pageParams.value.page === 1
    loadMoreStatus.value = 'loading'

    const params: GetReadingHistoryParams = {
      page: pageParams.value.page,
      size: pageParams.value.size,
    }

    const response = await getReadingHistory(params)
    if (response && response.code === 0 && response.data) {
      // 后端返回的是 List<ReadingHistoryRespVO>，不是分页格式
      const list = response.data

      if (isRefresh) {
        records.value = list
      }
      else {
        records.value.push(...list)
      }

      // 更新分页参数
      pageParams.value.page++

      // 检查是否还有更多数据（如果返回的数据少于请求的size，说明没有更多了）
      hasMore.value = list.length >= pageParams.value.size
    }
  }
  catch (error: any) {
    console.error('加载阅读记录失败:', error)

    // 检查是否是401错误（已经在拦截器中处理跳转）
    if (error?.data?.code === 401 || error?.statusCode === 401) {
      console.log('401错误已处理，用户将跳转到登录页面')
      return
    }

    uni.showToast({
      title: handleReadingRecordsError(error),
      icon: 'none',
    })
  }
  finally {
    loading.value = false
    loadMoreStatus.value = hasMore.value ? 'more' : 'noMore'
  }
}

// 刷新数据
async function refreshData() {
  await Promise.all([
    loadReadingStats(),
    loadReadingRecords(true),
  ])
}

// 加载更多
function loadMore() {
  if (hasMore.value && loadMoreStatus.value !== 'loading') {
    loadReadingRecords(false)
  }
}

// 记录点击
function onRecordClick(record: ReadingHistoryRespVO) {
  // 跳转到绘本集详情页
  if (record.bookSetId) {
    uni.navigateTo({
      url: `/pages-sub/reading/picture-book-set/index?setId=${record.bookSetId}&title=${encodeURIComponent(record.bookSetTitle || '绘本集')}`,
    })
  }
  else {
    uni.showToast({
      title: '绘本集信息不完整',
      icon: 'none',
    })
  }
}

// 记录长按
function onRecordLongPress(record: ReadingHistoryRespVO) {
  uni.showActionSheet({
    itemList: ['删除记录'],
    success: (res) => {
      if (res.tapIndex === 0) {
        onDeleteRecord(record)
      }
    },
  })
}

// 删除记录
function onDeleteRecord(record: ReadingHistoryRespVO) {
  deleteRecord.value = record
  deletePopup.value.open()
}

// 确认删除记录
async function confirmDeleteRecord() {
  if (!deleteRecord.value)
    return

  try {
    uni.showLoading({
      title: '删除中...',
    })

    const response = await deleteReadingRecord(deleteRecord.value.id)
    if (response && response.code === 0) {
      // 从列表中移除
      records.value = records.value.filter(record => record.id !== deleteRecord.value!.id)

      // 刷新统计数据
      loadReadingStats()

      uni.showToast({
        title: '删除成功',
        icon: 'success',
      })
    }
  }
  catch (error) {
    console.error('删除记录失败:', error)
    uni.showToast({
      title: handleReadingRecordsError(error),
      icon: 'none',
    })
  }
  finally {
    uni.hideLoading()
    deletePopup.value.close()
    deleteRecord.value = null
  }
}

// 取消删除记录
function cancelDeleteRecord() {
  deletePopup.value.close()
  deleteRecord.value = null
}

// 清空所有记录
function clearAllHistory() {
  clearPopup.value.open()
}

// 确认清空记录
async function confirmClearHistory() {
  try {
    uni.showLoading({
      title: '清空中...',
    })

    const response = await clearAllReadingRecords()
    if (response && response.code === 0) {
      records.value = []

      // 刷新统计数据
      loadReadingStats()

      uni.showToast({
        title: '清空成功',
        icon: 'success',
      })
    }
  }
  catch (error) {
    console.error('清空记录失败:', error)
    uni.showToast({
      title: handleReadingRecordsError(error),
      icon: 'none',
    })
  }
  finally {
    uni.hideLoading()
    clearPopup.value.close()
  }
}

// 取消清空记录
function cancelClearHistory() {
  clearPopup.value.close()
}

// 获取删除确认文本
function getDeleteConfirmText() {
  return deleteRecord.value ? `确定要删除"${deleteRecord.value.bookTitle}"的阅读记录吗？` : '确定要删除阅读记录吗？'
}

// 封面加载错误
function onCoverError() {
  console.log('封面加载失败')
}

// 页面生命周期
onLoad(() => {
  // 检查登录状态
  if (checkLoginStatus()) {
    loadReadingStats()
    loadReadingRecords(true)
  }
})

onShow(() => {
  // 页面显示时刷新数据
  refreshData()
})

// 下拉刷新
onPullDownRefresh(() => {
  refreshData().finally(() => {
    uni.stopPullDownRefresh()
  })
})

// 上拉加载更多
onReachBottom(() => {
  loadMore()
})
</script>

<template>
  <view class="reading-history-container">
    <!-- 头部标题 -->
    <view class="header">
      <text class="title">
        阅读记录
      </text>
      <view class="header-actions">
        <view class="refresh-btn" @click="refreshData">
          <uni-icons type="refresh" size="20" color="#333" />
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading && records.length === 0" class="loading-container">
      <uni-load-more status="loading" content-text="{ contentText: { contentdown: '加载中...', contentrefresh: '加载中...', contentnomore: '加载中...' } }" />
    </view>

    <!-- 阅读统计 -->
    <view v-else class="stats-section">
      <view v-if="stats" class="stats-grid">
        <view class="stat-item">
          <text class="stat-value">
            {{ stats.todayBooks || 0 }}
          </text>
          <text class="stat-label">
            今日阅读
          </text>
        </view>
        <view class="stat-item">
          <text class="stat-value">
            {{ stats.weekBooks || 0 }}
          </text>
          <text class="stat-label">
            本周阅读
          </text>
        </view>
        <view class="stat-item">
          <text class="stat-value">
            {{ stats.totalBooks || 0 }}
          </text>
          <text class="stat-label">
            总阅读数
          </text>
        </view>
        <view class="stat-item">
          <text class="stat-value">
            {{ Math.floor((stats.totalReadingTime || 0) / 60) }}
          </text>
          <text class="stat-label">
            总时长(小时)
          </text>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button class="clear-btn" :disabled="records.length === 0" @click="clearAllHistory">
          清空记录
        </button>
      </view>
    </view>

    <!-- 阅读记录列表 -->
    <view class="history-content">
      <!-- 空状态 -->
      <view v-if="records.length === 0 && !loading" class="empty-state">
        <view class="empty-icon">
          <uni-icons type="calendar" size="80" color="#ddd" />
        </view>
        <text class="empty-text">
          还没有阅读记录
        </text>
        <text class="empty-tips">
          开始阅读绘本，记录美好时光~
        </text>
      </view>

      <!-- 记录列表 -->
      <view v-else class="history-list">
        <view
          v-for="record in records"
          :key="getRecordKey(record)"
          class="history-card"
          @click="onRecordClick(record)"
          @longpress="onRecordLongPress(record)"
        >
          <view class="book-cover">
            <image
              :src="processBookCover(record.bookCover)"
              mode="aspectFill"
              class="cover-image"
              @error="onCoverError"
            />
            <view v-if="record.isCompleted" class="completed-badge">
              <uni-icons type="checkmarkempty" size="12" color="#fff" />
            </view>
          </view>

          <view class="book-info">
            <text class="book-title">
              {{ record.bookTitle }}
            </text>
            <view class="reading-meta">
              <text class="reading-time">
                {{ formatReadingDate(record.lastReadAt) }}
              </text>
            </view>
          </view>

          <view class="record-actions">
            <view class="action-btn" @click.stop="onDeleteRecord(record)">
              <uni-icons type="trash" size="16" color="#ff6b6b" />
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="hasMore" class="load-more">
          <uni-load-more
            :status="loadMoreStatus"
            content-text="{ contentText: { contentdown: '上拉加载更多', contentrefresh: '加载中...', contentnomore: '没有更多了' } }"
            @click-load-more="loadMore"
          />
        </view>

        <!-- 没有更多数据 -->
        <view v-else-if="records.length > 0" class="no-more-data">
          <text>没有更多了</text>
        </view>
      </view>
    </view>

    <!-- 删除确认弹窗 -->
    <uni-popup ref="deletePopup" type="dialog">
      <uni-popup-dialog
        type="warn"
        title="确认删除"
        :content="getDeleteConfirmText()"
        @confirm="confirmDeleteRecord"
        @close="cancelDeleteRecord"
      />
    </uni-popup>

    <!-- 清空确认弹窗 -->
    <uni-popup ref="clearPopup" type="dialog">
      <uni-popup-dialog
        type="warn"
        title="确认清空"
        content="确定要清空所有阅读记录吗？此操作不可恢复！"
        @confirm="confirmClearHistory"
        @close="cancelClearHistory"
      />
    </uni-popup>
  </view>
</template>

<style lang="scss" scoped>
.reading-history-container {
  background-color: #f8f9fa;
  min-height: 100vh;
}

.header {
  padding: 15px 20px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #f0f0f0;

  .title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }

  .header-actions {
    .refresh-btn {
      padding: 8px;
      border-radius: 50%;
      background-color: #f5f5f5;
      transition: all 0.3s ease;

      &:active {
        background-color: #e0e0e0;
        transform: scale(0.95);
      }
    }
  }
}

.loading-container {
  padding: 50px 20px;
  text-align: center;
}

.stats-section {
  background-color: #fff;
  padding: 20px;
  margin: 15px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 15px;
    margin-bottom: 20px;

    .stat-item {
      text-align: center;
      padding: 10px;
      border-radius: 8px;
      background-color: #f8f9ff;

      .stat-value {
        display: block;
        font-size: 24px;
        font-weight: bold;
        color: #667eea;
        margin-bottom: 6px;
      }

      .stat-label {
        font-size: 12px;
        color: #666;
      }
    }
  }

  .action-buttons {
    .clear-btn {
      width: 100%;
      height: 44px;
      line-height: 44px;
      font-size: 14px;
      color: #ff6b6b;
      background-color: #fff5f5;
      border: 1px solid #ffebee;
      border-radius: 8px;
      transition: all 0.3s ease;

      &:disabled {
        color: #ccc;
        background-color: #f5f5f5;
        border-color: #e0e0e0;
      }

      &:not(:disabled):active {
        background-color: #ffebee;
        transform: scale(0.98);
      }

      &::after {
        border: none;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;

  .empty-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 120px;
    height: 120px;
    margin-bottom: 20px;
    opacity: 0.6;
  }

  .empty-text {
    font-size: 16px;
    color: #666;
    margin-bottom: 8px;
  }

  .empty-tips {
    font-size: 14px;
    color: #999;
  }
}

.history-content {
  padding: 0 15px;
}

.history-list {
  .history-card {
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    }

    .book-cover {
      width: 60px;
      height: 75px;
      border-radius: 8px;
      margin-right: 15px;
      position: relative;
      overflow: hidden;
      background-color: #f5f5f5;

      .cover-image {
        width: 100%;
        height: 100%;
        border-radius: 8px;
      }

      .completed-badge {
        position: absolute;
        top: 4px;
        right: 4px;
        width: 20px;
        height: 20px;
        background-color: rgba(76, 175, 80, 0.9);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .book-info {
      flex: 1;
      min-width: 0;

      .book-title {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        margin-bottom: 8px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .reading-meta {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;

        .reading-time {
          font-size: 12px;
          color: #999;
        }
      }
    }

    .record-actions {
      .action-btn {
        padding: 8px;
        border-radius: 50%;
        background-color: #fff5f5;
        transition: all 0.3s ease;

        &:active {
          background-color: #ffebee;
          transform: scale(0.9);
        }
      }
    }
  }
}

.load-more {
  padding: 20px 0;
}

.no-more-data {
  text-align: center;
  padding: 20px 0;
  font-size: 12px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .stats-section {
    margin: 10px;
    padding: 15px;

    .stats-grid {
      gap: 10px;

      .stat-item {
        padding: 8px;

        .stat-value {
          font-size: 20px;
        }
      }
    }
  }

  .history-content {
    padding: 0 10px;
  }

  .history-list .history-card {
    padding: 12px;
    margin-bottom: 10px;

    .book-cover {
      width: 50px;
      height: 65px;
      margin-right: 12px;
    }

    .book-info .book-title {
      font-size: 15px;
    }
  }
}
</style>
